package com.longrise.common.datasource.remote;

import android.text.TextUtils;

import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.loaddata.newloaddata.LoadDataManager4;
import com.longrise.android.loaddata.newloaddata.LoadDataManagerFather;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.utils.NetUtil;


import java.util.HashMap;
import java.util.UUID;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by callxkj on 2017/10/19.
 * 保易健康的网络请求类,初始化封装类.返回结果的过滤.
 */

public class LoadDataManager {

    private static LoadDataManager mLoadDataManager;
    private HashMap<String, String> mHeadmap;
    private String mBbuuid; //uuid 除非卸载 只会生成一次
    private String mAppVersion; //app版本号
    private String mToken; //apptoken 通过这个来判断当前用户是否是登录状态
    private ReloginBean mReloginBean; //token失效后重新登录的bean

    public static LoadDataManager getInstance() {
        if (mLoadDataManager == null) {
            synchronized (LoadDataManager.class) {
                if (mLoadDataManager == null) {
                    mLoadDataManager = new LoadDataManager();
                }
            }
        }
        return mLoadDataManager;
    }

    /**
     * LoadDataManager 初始化
     *
     * @param appVersion app版本号码
     */
    public void init(String appVersion) {
        this.mAppVersion = appVersion;
        CacheUtils.setString(RemoteConstants.SP_APP_VERSION, appVersion);
        LoadDataManager4.getInstance(AppUtil.getContext()).setRestateKey("resultstate");
        //4003:传到后台的token为空,,4004:传到后台的token失效了
        LoadDataManager4.getInstance(AppUtil.getContext()).setSessionTimeOutArray(new String[]{"4003", "4004"});
        mHeadmap = null;
    }

    /**
     * @return 获取app的版本号码
     */
    public String getAppVersion() {
        if (TextUtils.isEmpty(mAppVersion)) {
            mAppVersion = CacheUtils.getString(RemoteConstants.SP_APP_VERSION, null);
        }
        return mAppVersion;
    }

    /**
     * 设置token
     *
     * @param token app登录,注册,自动登录后 设置token
     */
    public void setToken(String token) {
        this.mToken = token;
        CacheUtils.setString(RemoteConstants.SP_REMOTE_APP_TOKEN, token);
        mHeadmap = null;
    }

    public String getToken() {
        if (TextUtils.isEmpty(mToken)) {
            mToken = CacheUtils.getString(RemoteConstants.SP_REMOTE_APP_TOKEN, null);
        }
        return mToken;
    }

    /**
     * 设置重新登录的bean
     */
    public void setReloginBean(ReloginBean reloginBean) {
        this.mReloginBean = reloginBean;
        //给base网络请求类 设置超时重新登录的bean
        EntityBean tempBean = new EntityBean();

        if (reloginBean == null) {
            CacheUtils.setString(RemoteConstants.SP_REMOTE_RELOGIN_BEAN, null);

            tempBean.set(LoadDataManagerFather.IP_KEY_NAME, "");
            tempBean.set(LoadDataManagerFather.SERVICENAME_KEY_NAME, "");
            tempBean.set(LoadDataManagerFather.PARAMBEAN_KEY_NAME, null);
        } else {

            String beanString = JSONSerializer.getInstance().Serialize(reloginBean);
            CacheUtils.setString(RemoteConstants.SP_REMOTE_RELOGIN_BEAN, beanString);

            tempBean.set(LoadDataManagerFather.IP_KEY_NAME, reloginBean.getServiceUrl());
            tempBean.set(LoadDataManagerFather.SERVICENAME_KEY_NAME, reloginBean.getServiceName());
            tempBean.set(LoadDataManagerFather.PARAMBEAN_KEY_NAME, reloginBean.getBean());
        }
        LoadDataManager4.getInstance(AppUtil.getContext()).setLoginInfoBean(tempBean);
    }

    /**
     * @return 重新登录的bean
     */
    public ReloginBean getReloginBean() {
        if (mReloginBean == null) {
            String reloginString = CacheUtils.getString(RemoteConstants.SP_REMOTE_RELOGIN_BEAN, null);
            if (TextUtils.isEmpty(reloginString)) {
                mReloginBean = null;
            } else {
                mReloginBean = (ReloginBean) JSONSerializer.getInstance().DeSerialize(reloginString, ReloginBean.class);
            }
        }
        return mReloginBean;
    }

    /**
     * 获取网络请求中的cookie
     */
    public String getCookie() {
        return LoadDataManager4.getInstance(AppUtil.getContext()).getCookieString();
    }

    /**
     * 设置cookie
     */
    public void setCookie(String url, String cookie) {
        HttpUrl parse = HttpUrl.parse(url);
        Cookie cookie1 = Cookie.parse(parse, cookie);
        LoadDataManager4.getInstance(AppUtil.getContext()).addCookie(parse, cookie1, cookie);
    }

    /**
     * 设置重新登录类的绝对路径 用于反射
     */
    public void setReloginPath(String path) {
        LoadDataManager4.getInstance(AppUtil.getContext()).setLoginAgainClassFullPath(path);
    }


    /**
     * 获取uuid
     * 2017-06-12 xkj
     */
    public String getBYJKUUID() {
        if (mBbuuid != null) {
            return mBbuuid;
        } else {
            mBbuuid = CacheUtils.getString(RemoteConstants.SP_REMOTE_APP_UUID, null);
            if (TextUtils.isEmpty(mBbuuid)) {
                mBbuuid = UUID.randomUUID().toString().replace("-", "");
                CacheUtils.setString(RemoteConstants.SP_REMOTE_APP_UUID, mBbuuid);
                return mBbuuid;
            } else {
                return mBbuuid;
            }
        }
    }


    //请求头
    private HashMap<String, String> getHeadMap() {
        if (mHeadmap == null) {
            mHeadmap = new HashMap<String, String>();
            mHeadmap.put("App-Version", getAppVersion());
            mHeadmap.put("OSType", "android");
            mHeadmap.put("apptoken", getToken());
            mHeadmap.put("bbkey", getBYJKUUID());
        }
        return mHeadmap;
    }


    /**
     * 网络请求类  兼容以前的请求
     *
     * @param key                   设置标记
     * @param serviceUrl            url
     * @param serviceName           服务名称
     * @param bean                  请求bean
     * @param onRequestCallListener 回调监听
     */
    public void callService(final String key, final String serviceUrl, final String serviceName,
                            final EntityBean bean, final OnRequestCallListener onRequestCallListener) {
        if (!NetUtil.checkNetEnable()) {
            onRequestCallListener.onError(key, serviceName, new Throwable(), false);
            onRequestCallListener.onFinished(key, serviceName);
        } else {
            HashMap<String, String> headMap = getHeadMap();
            LoadDataManager4.getInstance(AppUtil.getContext()).callService4(key, serviceUrl, serviceName, bean, false, headMap, new LoadDataManagerFather.OnRequestCompleteListener() {
                @Override
                public void onSuccess(String key, String service, Object result) {
                    onRequestCallListener.onSuccess(key, service, result);
                }

                @Override
                public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                    onRequestCallListener.onError(key, service, new Throwable(), false);
                }

                @Override
                public void onFinished(String key, String service) {
                    onRequestCallListener.onFinished(key, service);
                }
            });
        }
    }


    public interface OnRequestCallListener {
        void onSuccess(String key, String service, Object result);

        void onError(String key, String service, Throwable ex, boolean isOnCallback);

        void onFinished(String key, String service);
    }


    /**
     * 新接口使用这个作为网络请求类
     *
     * @param key                    设置标记
     * @param serviceUrl             url
     * @param serviceName            服务名称
     * @param bean                   请求bean
     * @param onRequestCallListener2 回调监听
     */
    public void callService2(final String key, final String serviceUrl, final String serviceName,
                             final EntityBean bean, final OnRequestCallListener2 onRequestCallListener2) {
        if (!NetUtil.checkNetEnable()) {
            onRequestCallListener2.onError(key, serviceName, LoadDataManagerFather.ResultType.NoNetWorks);
            onRequestCallListener2.onFinished(key, serviceName);
        } else {
            HashMap<String, String> headMap = getHeadMap();
            LoadDataManager4.getInstance(AppUtil.getContext()).callService4(key, serviceUrl, serviceName,
                    bean, false, headMap, new LoadDataManagerFather.OnRequestCompleteListener() {
                        @Override
                        public void onSuccess(String key, String service, Object result) {
                            onRequestCallListener2.onSuccess(key, service, result);
                        }

                        @Override
                        public void onError(String key, String service, LoadDataManagerFather.ResultType resultType) {
                            onRequestCallListener2.onError(key, service, resultType);
                        }

                        @Override
                        public void onFinished(String key, String service) {
                            onRequestCallListener2.onFinished(key, service);
                        }
                    });
        }
    }


    public interface OnRequestCallListener2 extends LoadDataManagerFather.OnRequestCompleteListener {
        void onSuccess(String key, String service, Object result);

        void onError(String key, String service, LoadDataManagerFather.ResultType resultType);

        void onFinished(String key, String service);
    }


    /**
     * 新接口使用这个作为网络请求类
     * 这个用于内部 重新登录使用 项目中不要使用这个去请求方法
     */
    public void callServiceRelogin(final String key, final String serviceUrl, final String serviceName,
                                   final EntityBean bean, final LoadDataManagerFather.OnRequestCompleteListener onRequestCallListener) {
        HashMap<String, String> headMap = getHeadMap();
        LoadDataManager4.getInstance(AppUtil.getContext()).callService4(key, serviceUrl, serviceName,
                bean, false, headMap, onRequestCallListener);
    }


    /**
     * 做一些清除状态的操作
     */
    public void onDestory() {
        mLoadDataManager = null;
    }

}
